package com.example.project.dao.impl;

import com.example.project.dao.IDepartmentDao;
import com.example.project.entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 *作者：金照富
 * 2023年11月3日
 */
@Repository
public class IDepartmentDaoImpl implements IDepartmentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int insertDepartment(Department department) {
        return jdbcTemplate.update(
                "insert into department(departmentId,DepartmentName,DepartmentGrade) " +
                        "values(?,?,?)"
                ,department.getDepartmentId()
                ,department.getDepartmentName()
                ,department.getDepartmentGrade()
        );
    }

    @Override
    public int deleteDepartment(Department department) {
        return jdbcTemplate.update(
                "delete from department " +
                "where DepartmentID=?",department.getDepartmentId());

    }

    @Override
    public int updateDepartment(Department department) {
        return jdbcTemplate.update("update department set " +
                "DepartmentID=?,DepartmentName=?,DepartmentGrade=?"
                ,department.getDepartmentId()
                ,department.getDepartmentName()
                ,department.getDepartmentGrade()
        );
    }

    @Override
    public List<Department> getAllDepartment(Department department) {
        if(department.getDepartmentName()!=null)
            return jdbcTemplate.query("select " +
                "departmentId,DepartmentName,DepartmentGrade " +
                "from department where DepartmentName='"+department.getDepartmentName()+"'",new Object[]{},
                new BeanPropertyRowMapper<>(Department.class));
        else
            return jdbcTemplate.query("select " +
                "departmentId,DepartmentName,DepartmentGrade " +
                "from department",new Object[]{},
                new BeanPropertyRowMapper<>(Department.class));
    }

    @Override
    public Department getDepartment(Department department) {
        List<Department> result=jdbcTemplate.query("select " +
                                "departmentId,DepartmentName,DepartmentGrade " +
                                "from department where DepartmentName='"+department.getDepartmentName()+"'",
                        new Object[]{},
                        new BeanPropertyRowMapper<>(Department.class));
        if (result.size()>=1)
            return result.get(0);
        else return null;
    }
}
